﻿using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Threading.Tasks;
using Windows.Storage;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;

namespace BlogApp.WP8.ViewModel
{
    public class DataViewModel : ViewModelBase
    {
        public RelayCommand LoadDataCommand { get; private set; }

        private bool _isLoading = false;
        public bool IsLoading
        {
            get { return _isLoading; }
            set { _isLoading = value; RaisePropertyChanged("IsLoading"); }
        }

        public DataViewModel()
        {
            LoadDataCommand = new RelayCommand(loadData);
        }

        private void loadData()
        {
            LoadData();
        }

        public virtual async Task LoadData()
        {
            
        }

        #region IsolatedStorage

        StorageFolder _folder = ApplicationData.Current.LocalFolder;

        internal void SaveSetting(string key, object obj)
        {
            if (HasSetting(key))
            {
                IsolatedStorageSettings.ApplicationSettings[key] = obj;
            }
            else
            {
                IsolatedStorageSettings.ApplicationSettings.Add(key, obj);
            }
            IsolatedStorageSettings.ApplicationSettings.Save();
        }

        internal object LoadSetting(string key)
        {
            if (HasSetting(key))
            {
                return IsolatedStorageSettings.ApplicationSettings[key];
            }
            else
            {
                return false;
            }
        }

        internal bool HasSetting(string key)
        {
            return IsolatedStorageSettings.ApplicationSettings.Contains(key);
        }

        internal async Task SaveFile(string fileName, byte[] content)
        {
            StorageFile file = await _folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

            using (Stream s = await file.OpenStreamForWriteAsync())
            {
                await s.WriteAsync(content, 0, content.Length);
            }
        }

        internal async Task<byte[]> LoadFile(string fileName)
        {
            byte[] data;
            StorageFile file = await _folder.GetFileAsync(fileName);

            if (file != null)
            {
                using (Stream s = await file.OpenStreamForReadAsync())
                {
                    data = new byte[s.Length];
                    await s.ReadAsync(data, 0, (int)s.Length);
                }

                return data;
            }

            return null;
        }

        #endregion
    }
}